/*
 * Copyright 2013 JROSE
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.jrose.core.util;

import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import org.apache.commons.lang3.Validate;
import org.jrose.api.common.IterableFilter;

import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * Collections related helper utilities.
 *
 * @author Xiaohai Zhang
 * @since 2013-08-18 16:55
 */
@NoArgsConstructor(access = AccessLevel.PRIVATE)
abstract public class CollectionUtils {
    public static boolean isEmpty(Collection collection) {
        return collection == null || collection.isEmpty();
    }

    public static boolean isEmpty(Map map) {
        return map == null || map.isEmpty();
    }

    public static <T> T firstElement(Iterable<T> iterable) {
        if (iterable == null) {
            return null;
        }
        //noinspection LoopStatementThatDoesntLoop
        for (T element : iterable) {
            return element;
        }
        return null;
    }

    public static <T> List<T> filterIterable(Iterable<T> iterable, IterableFilter<T> filter) {
        Validate.notNull(filter, "Filter must not be null");
        List<T> result = new LinkedList<>();
        if (iterable == null) {
            return result;
        }
        for (T element : iterable) {
            if (filter.accept(element)) {
                result.add(element);
            }
        }
        return result;
    }

    public static <T> void addNonNullElement(Collection<T> collection, T element) {
        Validate.notNull(collection, "Target collection must not be null");
        if (element != null) {
            collection.add(element);
        }
    }
}
